package cn.springcloud.book.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;

@Slf4j
public class UserUtil {

    //工具类方法

    /**
     * 获取jwt中的claims信息
     *
     * @param token
     * @return claim
     */
    public static Claims getClaims(String token) {
        String key = Base64.getEncoder().encodeToString("springcloud123".getBytes());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * 获取请求中的userId
     *
     * @param request
     * @return userId
     */
    public static Integer getUserId(HttpServletRequest request) {
        String token = getToken(request);
        if (token == null) {
            return null;
        }
        Claims claims = getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        log.info("获取userId成功，值为" + userId.toString());
        return userId;
    }

    /**
     * 获取请求中的token
     *
     * @param request
     * @return token
     */
    public static String getToken(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            return null;
        }
        String token = authorization.split(" ")[1];
        log.info("获取token成功，值为{}", token);
        return token;
    }
}
